/*
 * @(#) StartupListener.java 2011-4-18
 *
 * Copyright (c) 2011, Strong Technology. All Rights Reserved.
 * Strong Technology. CONFIDENTIAL
 */
package cn.strong.gweva.common.listener;

import java.math.BigDecimal;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.strong.gweva.common.business.entity.Environment;
import cn.strong.gweva.common.business.entity.db.JxkhConfigEntity;
import cn.strong.gweva.common.business.entity.db.JxkhLegalDaysEntity;
import cn.strong.gweva.common.util.EntityUtility;
import cn.strong.gweva.system.business.service.ConfigService;
import cn.strong.gweva.system.business.service.LegalDaysService;

import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;

/**
 * 应用程序启动监听。
 * 
 * @author HMI
 * @version 1.0
 * @since 2011-4-18
 */
public class StartupListener implements ServletContextListener {
	private static final Logger log = LoggerFactory.getLogger(StartupListener.class);

	/* (non-Javadoc)
	 * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
	 */
	public void contextDestroyed(ServletContextEvent arg0) {
	}

	/* (non-Javadoc)
	 * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
	 */
	public void contextInitialized(ServletContextEvent arg0) {
		ServletContext sc = arg0.getServletContext();
		ApplicationContext actx = WebApplicationContextUtils.getWebApplicationContext(sc);
		
		try {
			// 设置系统配置信息
			this.setConfigInfo(actx);
			this.setLegalDaysList(actx);
		} catch (Exception e) {
			log.error("error", e);
		}
	}
	
	/**
	 * 设定配置信息
	 * 
	 * @param actx
	 * @throws Exception
	 */
	private void setConfigInfo(ApplicationContext actx) throws Exception
	{
		ConfigService configService = (ConfigService) actx.getBean("configService");
		
		JxkhConfigEntity configEntity = configService.searchConfig();
		
		if (configEntity == null || configEntity.getConfigId() == null)
		{
			configEntity = new JxkhConfigEntity();
			configEntity.setBaseScore(new BigDecimal(0));
			
			configService.updateConfig(configEntity);
		}
		
		EntityUtility.copyDBEntity(configEntity, Environment.CONFIG);
	}
	
	/**
	 * 设定法定天数
	 * 
	 * @param actx
	 * @throws Exception
	 */
	private void setLegalDaysList(ApplicationContext actx) throws Exception
	{
		LegalDaysService legalDaysService = (LegalDaysService) actx.getBean("legalDaysService");
		List<JxkhLegalDaysEntity> list = legalDaysService.searchLegalDaysList4Compute();
		
		Environment.LEGAL_DAYS_LIST.clear();
		if (list != null)
		{
			Environment.LEGAL_DAYS_LIST.addAll(list);
		}
	}

}
